package org.birtserver.backend.dao.parameters;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.beans.factory.annotation.Required;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;
import org.springframework.transaction.annotation.Transactional;

class ParameterRowMapper implements ParameterizedRowMapper<Object> {
  
  private Map<String, String> parameters = new HashMap<String, String>();
  
  @Override
  public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
    parameters.put(rs.getString("pkey"), rs.getString("pvalue"));
    return null;
  }
  
  public Map<String, String> getParameters() {
    return parameters;
  }
  
}

@Transactional
public class ParametersDaoImpl extends SimpleJdbcDaoSupport implements
    ParametersDao {

  private String queryGetGlobalParameters;
  
  private String queryDeleteAllGlobalParameters;

  private String queryAddGlobalParameter;
  
  @Override
  public Map<String, String> getGlobalParameters() {
    
    ParameterRowMapper rowMapper = new ParameterRowMapper();
    
    getSimpleJdbcTemplate().query(
        queryGetGlobalParameters, 
        rowMapper, 
        new Object[] {});
        
    return rowMapper.getParameters();
    
  }

  @Override
  public void saveGlobalParameters(Map<String, String> parameters) {
    
    //delete all parameters
    getSimpleJdbcTemplate().update(queryDeleteAllGlobalParameters, new Object[] {});
    
    for (Entry<String, String> entry : parameters.entrySet()) {
      getSimpleJdbcTemplate().update(
          queryAddGlobalParameter, 
          new Object[] { entry.getKey(), entry.getValue() });
    }
        
  }

  @Required
  public void setQueryGetGlobalParameters(String queryGetGlobalParameters) {
    this.queryGetGlobalParameters = queryGetGlobalParameters;
  }
  
  @Required
  public void setQueryAddGlobalParameter(String queryAddGlobalParameter) {
    this.queryAddGlobalParameter = queryAddGlobalParameter;
  }
  
  @Required
  public void setQueryDeleteAllGlobalParameters(
      String queryDeleteAllGlobalParameters) {
    this.queryDeleteAllGlobalParameters = queryDeleteAllGlobalParameters;
  }
  
}
